package com.whfc.emp.redis.impl;

import com.alibaba.fastjson.JSON;
import com.whfc.common.face.szyc.SearchPerson;
import com.whfc.emp.redis.MqttEmpRedisDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qzexing
 * @version 1.0
 * @date 2022/1/5 15:55
 */
@Repository
public class MqttEmpRedisDaoImpl implements MqttEmpRedisDao {

    public static final String KEY = "emp-code-list:dept-id:{0}";

    public static final String QUERY_PERSON_KEY = "emp:mqtt:query-person-key";

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void saveEmpCodeList(Integer deptId, List<String> empCodeList) {
        String key = MessageFormat.format(KEY, deptId);
        String value = JSON.toJSONString(empCodeList);
        redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public List<String> getEmpCodeList(Integer deptId) {
        String key = MessageFormat.format(KEY, deptId);
        String value = redisTemplate.opsForValue().get(key);
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotBlank(value)) {
            list = JSON.parseArray(value, String.class);
        }
        return list;
    }

    @Override
    public Integer getMqttTopicSize() {
        int size = 0;
        Long s = redisTemplate.opsForList().size(QUERY_PERSON_KEY);
        if (s != null) {
            size = Math.toIntExact(s);
        }
        return size;
    }


    @Override
    public void saveMqttTopic(SearchPerson searchPerson) {
        if (searchPerson == null) {
            return;
        }
        String value = JSON.toJSONString(searchPerson);
        redisTemplate.opsForList().rightPush(QUERY_PERSON_KEY, value);
    }

    @Override
    public SearchPerson getMqttTopic() {
        String value = redisTemplate.opsForList().leftPop(QUERY_PERSON_KEY);
        return JSON.parseObject(value, SearchPerson.class);
    }
}
